package com.bdqn.t320.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * 创建链接工具类
 */
public class MyBatisUtil {

    //SqlSessionFactory 实例
    private static SqlSessionFactory factory;

    static {
        String resource = "mybatis-config.xml";
        //获取对mybatis-config.xml文件的输入流
        InputStream is = null;
        try {
            is = Resources.getResourceAsStream(resource);
            factory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //返回SqlSession实例
    public static SqlSession createSqlSession() {
        return factory.openSession(true);
    }

    //关闭SqlSession实例
    public static void closeSqlSession(SqlSession sqlSession) {
        if (sqlSession != null) {
            sqlSession.close();
        }
    }
}
